package com.huafv.flyauth.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huafv.flyauth.core.redis.RedisCache;
import com.huafv.flyauth.security.handle.LoginFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        /*System.out.println(url);*/

        if ("/user/login".equals(url) && request.getMethod().equals("POST")) {
            try {
                // 校验验证码
                validate(request);
            } catch (AuthenticationException e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }

        filterChain.doFilter(request, response);
    }

    // 校验验证码逻辑
    private void validate(HttpServletRequest httpServletRequest) {

        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("token");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            // TODO 错误捕获
            throw new BadCredentialsException("验证码错误");
        }

        if (!code.equals(redisCache.getCacheObject("UUID:" + key))) {
            throw new BadCredentialsException("验证码错误");
        }
        // 一次性使用
        redisCache.deleteObject("UUID:" + key);
    }
}
